//
//  BDLocationSrver.m
//  BadBoy
//
//  Created by wen on 2017/3/29.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDLocationServer.h"


#define kLocationDataPath   [CachePaths stringByAppendingPathComponent:@"location.data"]

@interface BDLocationModel ()

@property (nonatomic, assign) NSTimeInterval timeInterval;

@end

@implementation BDLocationModel

- (instancetype)initWithObject:(AMapLocationReGeocode *)object{
    if (self = [super init]) {
        self.formattedAddress = object.formattedAddress;
        self.country = object.country;
        self.province = object.province;
        self.city = object.city;
        self.district = object.district;
        self.citycode = object.citycode;
        self.adcode = object.adcode;
        self.street = object.street;
        self.number = object.number;
        self.POIName = object.POIName;
        self.AOIName = object.AOIName;
    }
    return self;
}

- (void)saveLocationInfo{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = date.timeIntervalSince1970;
    self.timeInterval = timeInterval;
    
    NSDictionary *dic = self.mj_keyValues;
    if ([dic writeToFile:kLocationDataPath atomically:YES]) {
        // BDLog(ASLocalizedString(@"保存地址信息成功"));
    }
}

+ (instancetype)getLocationInfo{
    __block BDLocationModel *location = [self mj_objectWithKeyValues:[NSDictionary dictionaryWithContentsOfFile:kLocationDataPath]];
    if ([BDLocationServer whetherOpenLocationServer] == NO || location == nil) {
        NSDictionary *dic = @{
                              @"longitude" : @113.3329768880208,
                              @"province" : @"广东省",
                              @"latitude" : @23.13247151692708,
                              @"street" : @"天河南二路",
                              @"AOIName" : @"华润万家(天河东店)",
                              @"formattedAddress" : @"广东省广州市天河区天河南二路靠近招商银行(广州丰兴支行)",
                              @"timeInterval" : @0,
                              @"city" : @"广州市",
                              @"citycode" : @"020",
                              @"district" : @"天河区",
                              @"adcode" : @"440106",
                              @"number" : @"27号",
                              @"country" : @"中国",
                              @"POIName" : @"招商银行(广州丰兴支行)"};
        return [BDLocationModel mj_objectWithKeyValues:dic];
    }else{
        NSDate *date = [NSDate date];
        NSTimeInterval timeInterval = date.timeIntervalSince1970;
        
        BOOL needLocation = NO;
        if (location == nil) {
            //第一次定位
            needLocation = YES;
        }else if (timeInterval - location.timeInterval > 600) {
            //上一次定位信息失效
            needLocation = YES;
        }
        
        if (needLocation == YES) {
            [[BDLocationServer sharedServer] locate];
        }
        return location;
    }
}

@end

#import <AMapLocationKit/AMapLocationKit.h>

@interface BDLocationServer ()<AMapLocationManagerDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic) int reLocationCount;
@end

@implementation BDLocationServer

+ (BOOL)whetherOpenLocationServer{
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        return YES;
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
        return NO;
    }
    return NO;
}

+ (instancetype)sharedServer{
    static BDLocationServer *shardServer;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shardServer = [[BDLocationServer alloc] init];
    });
    
    return shardServer;
}

+ (NSString *)getCurrentCity_id{
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    return [self getCityIdWithCityName:locationModel.city cityType:BDCityTypeCity];
}

+ (NSString *)getCityIdWithCityName:(NSString *)cityName cityType:(BDCityType)cityType{
    BDCityInfo *cityInfo = [BDCityInfo getCityWithName:cityName type:cityType];
    
    if (cityInfo) {
        return [NSString stringWithFormat:@"%@", @(cityInfo.infoID)];
    }
    return nil;
}

+ (CLLocationCoordinate2D)getLastCoordinate{
    CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([[[NSUserDefaults standardUserDefaults] objectForKey:@"lastLatitude"] doubleValue], [[[NSUserDefaults standardUserDefaults] objectForKey:@"lastLongitude"] doubleValue]);
    return coordinate;
}

- (void)locate{
    if ([BDLocationServer whetherOpenLocationServer] == YES) {
        //地理逆编码
        [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
            if (error){
                // BDLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
                if (error.code == AMapLocationErrorLocateFailed && _reLocationCount < 5){
                    _reLocationCount++;
                    [self locate];
                    return;
                }
            }
            //定位信息
            
            //逆地理信息
            if (regeocode){
                NSLog(ASLocalizedString(@"定位成功"));
                BDLocationModel *loationModel = [[BDLocationModel alloc] initWithObject:regeocode];
                loationModel.longitude = location.coordinate.longitude;
                loationModel.latitude = location.coordinate.latitude;
                if (![regeocode.city isNotBlank]) {
                    if ([regeocode.province containsString:ASLocalizedString(@"香港")]) {
                        loationModel.city = ASLocalizedString(@"香港特别行政区");
                    }else if ([regeocode.province containsString:ASLocalizedString(@"澳門")]) {
                        loationModel.city = ASLocalizedString(@"澳门特别行政区");
                    }else if ([regeocode.province containsString:ASLocalizedString(@"台湾")]) {
                        loationModel.city = ASLocalizedString(@"台湾");
                    }
                }
                [loationModel saveLocationInfo];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"locationFinishChangeButton" object:regeocode.city];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"DistrictNotification" object:nil];
            }
        }];
    }
}

- (void)locatonWithCityName:(NSString *)cityName{
    BDLocationModel *locationModel = [BDLocationModel getLocationInfo];
    if ([locationModel.city isEqualToString:cityName]) {
        [[NSUserDefaults standardUserDefaults] setObject:@(locationModel.longitude) forKey:@"lastLongitude"];
        [[NSUserDefaults standardUserDefaults] setObject:@(locationModel.latitude) forKey:@"lastLatitude"];
    }else{
        CLGeocoder * geocoder = [[CLGeocoder alloc] init];
        [geocoder geocodeAddressString:cityName completionHandler:^(NSArray *placemarks, NSError *error) {
            if(error) {
                // BDLog(@"Geocoder error : %@",error);
                return ;
            }
            if([placemarks count] == 0) {
                // BDLog(@"Could found the address.");
                return ;
            }
            CLPlacemark * placeMark = [placemarks objectAtIndex:0];
//            NSLog(@"%f %f",placeMark.location.coordinate.longitude,placeMark.location.coordinate.latitude);
            [[NSUserDefaults standardUserDefaults] setObject:@(placeMark.location.coordinate.longitude) forKey:@"lastLongitude"];
            [[NSUserDefaults standardUserDefaults] setObject:@(placeMark.location.coordinate.latitude) forKey:@"lastLatitude"];
        }];
    }
}

- (AMapLocationManager *)locationManager{
    if (!_locationManager) {
        self.locationManager = [[AMapLocationManager alloc] init];
        
        [_locationManager setDelegate:self];
        [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        
        [self.locationManager setLocationTimeout:6];
        
        [self.locationManager setReGeocodeTimeout:3];
    }
    return _locationManager;
}

@end
